<template>
  <div class="shopping-cart">
    <!-- 购物车头部 -->
    <van-nav-bar title="购物车">
      <template #right>
        <van-icon v-if="cartList.length > 0 && !isCartEmpty" name="delete-o" size="20" color="#ee0a24"
          @click="clearAllCart" class="clear-all-icon" />
      </template>
    </van-nav-bar>

    <!-- 购物车为空时显示 -->
    <div v-if="cartList.length === 0 || cartList.every(group => group.items.length === 0)" class="empty-cart">
      <van-empty image="cart" description="购物车为空">
        <van-button round type="primary" @click="goToHome">去点餐</van-button>
      </van-empty>
    </div>

    <!-- 购物车列表 -->
    <div v-else class="cart-content">
      <!-- 按商家分组显示商品 -->
      <div v-for="group in cartList" :key="group.merchantId" class="merchant-card">
        <!-- 商家信息栏 - 卡片头部 -->
        <div class="merchant-header">
          <div class="merchant-info">
            <div class="merchant-name">{{ group.merchantName }}</div>
          </div>
          <div class="merchant-actions">
            <van-icon name="delete-o" size="18" color="#999" @click="clearCart(group)" class="clear-merchant-icon" />
          </div>
        </div>

        <!-- 商品列表 - 卡片内容 -->
        <div class="product-list">
          <div v-for="item in group.items" :key="item.id" class="product-item">
            <div class="product-info">
              <van-checkbox :name="item.id" />
              <van-image :src="item.image" class="item-image" fit="cover" round />
              <div class="item-details">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">
                  <span class="current-price">¥{{ item.price }}</span>
                  <span class="original-price">¥{{ item.originalPrice }}</span>
                </div>
                <div class="item-spec">{{ item.spec }}</div>
              </div>
            </div>

            <div class="quantity-control">
              <van-stepper v-model="item.quantity" integer min="1" @change="(value) => onChangeQuantity(item, value)" />
            </div>
          </div>
        </div>
      </div>

      <!-- 底部结算栏 -->
      <van-submit-bar :price="totalPrice" button-text="去结算" @submit="onSubmit">
        <van-checkbox v-model="isAllChecked" @click="toggleAll">全选</van-checkbox>
        <template #tip>
          一共 {{ totalQuantity }} 件商品
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'ShoppingCartPage'
})
</script>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()

// 修改购物车数据结构，按商家分组
const cartList = ref([
  {
    merchantId: 1,
    merchantName: '一串成名·烧烤·龙虾·生蚝',
    deliveryTime: '58',
    promotion: '配送费减5',
    items: [
      {
        id: 1,
        name: '水煮花生',
        spec: '',
        price: 13.8,
        originalPrice: 25,
        quantity: 1,
        image: 'https://img.yzcdn.cn/vant/cat.jpeg'
      },
      {
        id: 2,
        name: '水煮毛豆',
        spec: '',
        price: 15,
        originalPrice: 25,
        quantity: 1,
        image: 'https://img.yzcdn.cn/vant/cat.jpeg'
      }
    ]
  }
])

// 选中的商品ID列表 - 改为使用对象映射
const checkedItemsMap = ref<{[key: number]: boolean}>({})

// 计算属性 - 获取所有选中的商品ID
const checkedItems = computed(() => {
  return Object.keys(checkedItemsMap.value)
    .filter(key => checkedItemsMap.value[Number(key)])
    .map(Number)
})

// 计算总价
const totalPrice = computed(() => {
  return cartList.value
    .flatMap(group => group.items)
    .filter(item => checkedItems.value.includes(item.id))
    .reduce((total, item) => total + item.price * item.quantity * 100, 0)
})

// 计算总数量
const totalQuantity = computed(() => {
  return cartList.value
    .flatMap(group => group.items)
    .filter(item => checkedItems.value.includes(item.id))
    .reduce((total, item) => total + item.quantity, 0)
})

// 检查是否全选
const isAllChecked = computed({
  get() {
    const allItemIds = cartList.value.flatMap(group => group.items.map(item => item.id))
    return allItemIds.length > 0 &&
      allItemIds.every(id => checkedItemsMap.value[id])
  },
  set(val) {
    // 这个setter不会被直接调用，而是通过toggleAll方法处理
  }
})

// 检查购物车是否为空
const isCartEmpty = computed(() => {
  return cartList.value.every(group => group.items.length === 0)
})

// 处理单个商品选择
const handleItemCheck = (checked: boolean) => {
  // 这个方法会在checkbox状态改变时被调用
  // 实际的状态已经在v-model中处理了
}

// 切换全选
const toggleAll = (checked: boolean) => {
  if (checked) {
    // 全选
    cartList.value.forEach(group => {
      group.items.forEach(item => {
        checkedItemsMap.value[item.id] = true
      })
    })
  } else {
    // 取消全选
    cartList.value.forEach(group => {
      group.items.forEach(item => {
        checkedItemsMap.value[item.id] = false
      })
    })
  }
}

// 方法定义
const onClickLeft = () => {
  router.go(-1)
}

const goToHome = () => {
  router.push('/')
}

const onChangeQuantity = (item: any, value: number) => {
  item.quantity = value
}

const onDelete = (item: any, group: any) => {
  const index = group.items.findIndex((i: any) => i.id === item.id)
  if (index !== -1) {
    group.items.splice(index, 1)
    // 从选中列表中移除
    delete checkedItemsMap.value[item.id]
  }
}

// 清空购物车
const clearCart = (group: any) => {
  showConfirmDialog({
    title: '确认清空',
    message: `确定要清空${group.merchantName}的所有商品吗？`,
  }).then(() => {
    // 清空当前商家的所有商品
    group.items = []

    // 从选中列表中移除这些商品
    group.items.forEach((item: any) => {
      delete checkedItemsMap.value[item.id]
    })

    showToast('已清空')
  }).catch(() => {
    // 取消操作
  })
}

// 清空所有购物车
const clearAllCart = () => {
  showConfirmDialog({
    title: '确认清空',
    message: '确定要清空购物车中所有的商品吗？',
  }).then(() => {
    // 清空所有商家的商品
    cartList.value.forEach(group => {
      group.items = []
    })

    // 清空选中列表
    checkedItemsMap.value = {}

    showToast('购物车已清空')
  }).catch(() => {
    // 取消操作
  })
}

const handleGroupChange = () => {
  // 处理选中项变化
}

const onSubmit = () => {
  if (checkedItems.value.length === 0) {
    showToast('请选择商品')
    return
  }

  // 跳转到订单确认页面
  router.push('/confirm-order')
}
</script>

<style scoped>
.shopping-cart {
  padding-bottom: 50px;
}

.empty-cart {
  padding-top: 100px;
}

.cart-content {
  background-color: #f5f5f5;
  border-radius: 14px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  flex-direction: row;
}

.merchant-card {
  background-color: #ffffff;
  border-radius: 12px;
  /* flex: 1; */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 10px;
  width: 95%;
  overflow: hidden;
}

.van-image__img {
  border-radius: 0px;
}

.merchant-header {
  padding: 5px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebedf0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.merchant-info {
  display: flex;
  flex-direction: column;
  font-size: 14px;
}

.merchant-name {
  font-weight: bold;
  color: #333;
}

.delivery-time {
  color: #999;
  font-size: 12px;
}

.merchant-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.merchant-promotion {
  color: #ee0a24;
  font-size: 12px;
  padding: 2px 8px;
  background-color: #fff7f7;
  border-radius: 4px;
}

.clear-cart-btn,
.clear-all-btn {
  height: 24px;
  line-height: 24px;
  font-size: 12px;
  border-radius: 12px;
  padding: 0 10px;
}

.product-list {
  padding: 10px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.product-item:last-child {
  border-bottom: none;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 2;
}

.item-image {
  width: 60px;
  height: 60px;
  margin: 0 10px;
  flex-shrink: 0;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.item-price {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.current-price {
  font-size: 16px;
  color: #ee0a24;
  font-weight: bold;
  margin-right: 5px;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.item-spec {
  font-size: 12px;
  color: #999;
}

.quantity-control {
  width: 80px;
  flex: 1;
}

:deep(.van-submit-bar) {
  bottom: 50px;
}
</style>